<template>
  <div class="container">
    <el-page-header @back="gobackFoods" content="添加商品页"> </el-page-header>
    <el-divider></el-divider>

    <el-row>
      <el-col :span="14" :offset="5">
        <header class="form_header">选择商品分类</header>
        <el-form
          :model="categoryForm"
          ref="categoryForm"
          label-width="110px"
          class="form"
        >
          <el-row class="category_select">
            <el-form-item label="商品分类">
              <el-select
                v-model="foodForm.category"
                placeholder="请选择商品分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categoryForm.categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row
            class="add_category_row"
            :class="showAddCategory ? 'showEdit' : ''"
          >
            <div class="add_category">
              <el-form-item label="商品分类" prop="name">
                <el-input v-model="categoryForm.name"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitCategoryForm('categoryForm')"
                  >提交</el-button
                >
              </el-form-item>
            </div>
          </el-row>
          <div class="add_category_button" @click="addCategoryFun">
            <i class="el-icon-caret-top edit_icon" v-if="showAddCategory"></i>
            <i class="el-icon-caret-bottom edit_icon" v-else slot="icon"></i>
            <span>添加商品分类</span>
          </div>
        </el-form>

        <!-- 添加区域 -->
        <header class="form_header">添加商品</header>
        <el-form
          :model="foodForm"
          ref="foodForm"
          label-width="110px"
          class="form food_form"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="foodForm.name"
              placeholder="请输入商品名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品原价" prop="priced">
            <el-input
              v-model="foodForm.priced"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入商品价格 只能为数字"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品现价" prop="price">
            <el-input
              v-model="foodForm.price"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入商品价格 只能为数字"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品库存" prop="stock">
            <el-input
              v-model="foodForm.stock"
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入商品库存 只能为数字"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input
              ref="upload"
              type="textarea"
              placeholder="请输入商品描述"
              v-model="foodForm.description"
              :rows="4"
              maxlength="100"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="上传图片">
            <el-upload
              class="upload-demo"
              ref="upload"
              :drag="true"
              :action="uploadpath"
              :before-upload="beforeImgUpload"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :limit="1"
              list-type="picture"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将图片拖到此处，或
                <em>点击上传</em>
              </div>
              <!-- <el-button size="small" type="primary">点击上传</el-button> -->
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addFood('foodForm')"
              >确认添加</el-button
            >
            <el-button
              type="info"
              icon="el-icon-refresh-right"
              @click="resetFood"
              >重置</el-button
            >
            <el-button icon="el-icon-d-arrow-left" @click="gobackFoods" plain
              >返回</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" class="previewImage" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryForm: {
        categoryList: [],
        name: '',
      },
      showAddCategory: false,
      foodForm: {
        category: '',
        name: '',
        priced: '',
        price: '',
        stock: '',
        description: '',
        imageName: '',
        imageURL: '',
      },
      uploadpath: this.URL.Upload,
      // 图片预览
      previewPath: '',
      // 预览对话框
      previewVisible: false,
    }
  },
  computed: {
    selectValue: function () {
      return (
        this.categoryForm.categoryList[this.categoryForm.categorySelect] || {}
      )
    },
  },
  watch: {
    $route() {
      // 对路由变化作出响应...
      this.getCategory()
    },
  },
  methods: {
    addCategoryFun() {
      this.showAddCategory = !this.showAddCategory
    },
    // 提交种类表单
    submitCategoryForm(categoryForm) {
      this.$refs[categoryForm].validate(async (valid) => {
        if (!valid) return
        const path = this.URL.Category
        const { data: res } = await this.$http
          .post(path, {
            data: {
              name: this.categoryForm.name,
            },
          })
          .catch(() => {
            this.$message.error('NETWORK ERROR')
          })
        if (res.status !== 200) {
          this.$message.error('提交失败')
        }
        this.$message.success('提交成功')
        this.getCategory()
      })
    },
    async getCategory() {
      const path = this.URL.Category
      const temp = []
      const { data: res } = await this.$http.get(path).catch(() => {
        this.$message.error('NETWORK ERROR')
      })
      res.forEach((element) => {
        temp.push(JSON.parse(element))
      })
      this.categoryForm.categoryList = temp

      // console.log(this.$router.params)
    },
    beforeImgUpload(file) {
      const isRightType =
        file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 3

      if (!isRightType) {
        this.$message.error('上传图片只能是 JPG 和 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isRightType && isLt2M
    },
    //处理图片上传成功的事件
    handleSuccess(response) {
      if (response.meta.status !== 200) {
        return this.$message.error('上传失败')
      }
      this.foodForm.imageURL = response.data.url
      this.foodForm.imageName = response.data.imageName
    },
    // 处理移除图片的操作
    async handleRemove(file) {
      // console.log(file)
      const path = this.URL.Upload
      const { response: res } = file
      await this.$http
        .patch(path, {
          data: {
            key: res.data.url,
          },
        })
        .catch((error) => error)
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
      console.log(this.$refs.upload)
    },
    handleExceed() {
      this.$message.info('只能上传一张图片')
    },
    // 添加商品
    addFood(foodForm) {
      this.$refs[foodForm].validate(async (valid) => {
        if (!valid) return
        const path = this.URL.AddFoods
        const { data: res } = await this.$http.post(path, {
          data: {
            ...this.foodForm,
          },
        })
        if (res.meta.status == 200) {
          this.$message.success('添加成功')
        }
        console.log(res)
      })
    },
    // 点击清空表单
    resetFood() {
      this.$refs.foodForm.resetFields()
      this.$refs.upload.clearFiles()
    },
    // 回到商品列表
    gobackFoods() {
      this.$router.push('/foods')
    },
  },
  created() {
    this.getCategory()
  },
}
</script>

<style lang="less">
.form {
  min-width: 400px;
  margin-bottom: 30px;
  &:hover {
    box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
      0 2px 4px 0 rgba(232, 237, 250, 0.5);
    border-radius: 6px;
    transition: all 400ms;
  }
}
.food_form {
  border: 1px solid #eaeefb;
  padding: 10px 10px 0;
}
.form_header {
  text-align: center;
  margin-bottom: 10px;
}
.category_select {
  border: 1px solid #eaeefb;
  padding: 10px 30px 10px 10px;
  border-top-right-radius: 6px;
  border-top-left-radius: 6px;
}
.add_category_row {
  height: 0;
  overflow: hidden;
  transition: all 400ms;
  background: #f9fafc;
}
.showEdit {
  height: 137px;
}
.add_category {
  background: #f9fafc;
  padding: 10px 30px 0px 10px;
  border: 1px solid #eaeefb;
  border-top: none;
}
.add_category_button {
  text-align: center;
  line-height: 40px;
  border-bottom-right-radius: 6px;
  border-bottom-left-radius: 6px;
  border: 1px solid #eaeefb;
  border-top: none;
  transition: all 400ms;
  &:hover {
    background: #f9fafc;
    span,
    .edit_icon {
      color: #20a0ff;
    }
  }
  .edit_icon {
    color: #ccc;
    transition: all 400ms;
  }
}

.previewImage {
  width: 100%;
}
</style>
